const redisClient = require("../redis/redisClient");
const errors = require("../agora/error");
const Stop = require("../agora/api/Stop");
const ControllerBase = require("../controller/ControllerBase");
const config = require("config");
const logger = require('../utils').getLogger(__filename);
const exitStatus = [6, 7, 8, 20]
const prefix = config.get('aliyun.storageConfig.fileNamePrefix')[0]

const modifyMeetingTimestampDiff = async (queryResult, meetingInfo, key) => {
	if (meetingInfo.sliceStartTime) {
		return
	}
	const { redisStartEventKey } = meetingInfo
	const sliceStartTime = queryResult.serverResponse.sliceStartTime;
	if (!sliceStartTime) {
		return
	}
	const values = await redisClient.getMeetingEventFields(redisStartEventKey, 'timestampUTC', 'timestamp', 'response')
	const data = [...values]
	data[0] = meetingInfo.sliceStartTime = sliceStartTime
	let diff = data[0] - data[2]
	data[1] = data[1] + diff;
	logger.info(`获取sliceStartTime:${sliceStartTime},diff:${diff},event fields:modify:${JSON.stringify(data)},origin:${JSON.stringify(values)}`);
	await redisClient.setMeetingInfo(key, meetingInfo)
	await redisClient.modifyMeetingEventFields(redisStartEventKey, 'timestampUTC', data[0], 'timestamp', data[1], 'response', data[2])
}
const writeEventWhenExitStatus = async (queryResult, meetingInfo, key) => {
	const status = queryResult.serverResponse.status;
	if (exitStatus.includes(status)) {
		const info = await redisClient.getMeetingInfo(key);
		if (info) {
			await writeStopEventByMeetingInfo(info)
			await redisClient.deleteMeetingInfo(key)
			logger.info(`ExitStatus-关闭录屏:${JSON.stringify(meetingInfo)}`)
		} else {
			logger.info(`key:${key} 已经处理完成`)
		}
	}
}

const writeEventWhenError400 = async (err, meetingInfo, key) => {

	const { response, status } = err
	if (!status) {
		logger.info(`错误结构不正确:${JSON.stringify(err)}`)
		return
	}
	if (err instanceof errors.Error400 || err instanceof errors.Error404) {
		const info = await redisClient.getMeetingInfo(key);
		if (info) {
			await writeStopEventByMeetingInfo(info)
			await redisClient.deleteMeetingInfo(key)
			logger.info(`Error400-关闭录屏:${JSON.stringify(meetingInfo)}`)
		} else {
			logger.info(`key:${key} 已经处理完成`)
		}
	}
}
const writeStopEventByMeetingInfo = async (meetingInfo) => {
	let { channelName, modal, resourceId, sid, rid, meetingId, events, type, uid, userId, } = meetingInfo
	const event = JSON.parse(events)
	const eventData = ControllerBase.createWriteData2(event.stop, userId, meetingId, channelName, uid, sid, type,modal,prefix)
	const rts = await redisClient.writeMeetingEvent(meetingId, eventData)
	logger.info(rts)
	logger.info(eventData)
}

const sendStopRequestByMeetingInfo = async (meetingInfo) => {
	let { channelName, modal, resourceId, sid, rid } = meetingInfo
	let stopRunner = new Stop({ channelName, rid, sid, resourceId }, modal);
	return stopRunner.run();
}
module.exports = {
	modifyMeetingTimestampDiff,
	writeEventWhenError400,
	writeEventWhenExitStatus
}
